<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Handles displaying, creating and editing all of the deposits.
 *
 * @author Charles
 */
class deposits {
    
    /**
     * Description: Displays Div map of deposits, ontop of terrain
     * 
     * @global object $terrain
     * 
     * @param int $planetID
     * @param int $planetSize
     */
    function drawDepositMap($planetID, $planetSize) {
        global $terrain;
        
        // setup for loop to loop through x coordinates, and then y
        for ($y = 0; $y <= $planetSize; $y++) {
            for ($x = 0; $x <= $planetSize; $x++) {
                $coordinates = $x.", ".$y;
                // Set a varaible for current terrain type
                $type = $terrain->getTerrainType($coordinates, $planetID);
                
                // If Coordinate doesn't equal none terain type display image
                if($type != 16 && $type != NULL && $type != '') {
                    // Check to see whether there is a deposit at coordinates
                    $hasDeposit = $this->hasDeposit(NULL, $planetID, $coordinates);
    
                    echo '<div class="'.$terrain->displayTerrainType($type).'">';
                    if($hasDeposit == true) {
                        $currDeposit = $this->getDeposit($planetID, $coordinates);
                        echo "<img src='".$this->depositImage($currDeposit['type'])."' 
                            class='rawMaterial'/>";
                    }
                    echo '</div>';
                } elseif($type == 16 || $type == NULL) {
                    echo '<div class="none"></div>';
                }
                
                // if all x's drawn do line break
                if ($x == $planetSize) {
                    echo "<br />";
                }
                
            }
        }
    }
    
    /**
     * Description: Counts Deposits
     * 
     * @global object $mysqli
     * @param int $planetID
     * @return int
     */
    function countDeposits($planetID) {
        global $mysqli;
        
        $query = "SELECT * FROM deposits WHERE planet_id = '$planetID'";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        $count = $result->num_rows;
        
        return $count;
        var_dump($count);
        
    }
    
    /**
     * Description: Creates deposit into database and redirects to listDeposits.php
     * 
     * @global object $mysqli
     * @global object $planets
     * @param string $name
     * @param int $size
     * @param string $planet
     * @param string $coordinates
     * @param int $type
     * 
     * @return void Redirects user.
     */
    function createDeposit($name, $size, $planet, $coordinates, $type) {
        global $mysqli;
        global $planets;

        /**
         * @todo Check to make sure everything is within paramteres
         */
        
        // turn planet name into planet id
        $planet = $planets->planetInfo(NUll, $planet);
        $planetID = $planet['id'];
        
        // check to see if there is already a deposit there
        $hasDeposit = $this->hasDeposit(NULL, $planetID, $coordinates);
        if($hasDeposit == true) {
            echo 'Error: Deposit at specified coordinates. <br />';
            echo 'Please <a href="createDeposit.php">try again</a>';
            exit();
        }
        
        $query = "INSERT INTO deposits VALUES ('', '$planetID', '$name', '$size',
            '$coordinates', '$type')";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        header("Location: listDeposits.php");
        
    }
    
    
    /**
     * 
     * Description: Checks whether a set of coordinates has a Deposit.
     * Can search by name or ID.
     * 
     * @global object $mysqli
     * @global object $planets
     * @param string $planetName
     * @param stirng $coordinates
     * @return boolean
     */
    function hasDeposit($planetName, $planetID=NULL, $coordinates) {
        global $mysqli;
        global $planets;
        
        if($planetName != NULL) {
        
            $planetInfo = $planets->planetInfo(NULL, $planetName);
            $planetID = $planetInfo['id'];

            $query = "SELECT * FROM deposits WHERE planet_id = '$planetID' AND
                    coordinates = '$coordinates'";
            $result = $mysqli->query($query) or die(mysqli_error($mysqli));

            $num_rows = $result->num_rows;
        } else {
            $query = "SELECT * FROM deposits WHERE planet_id = '$planetID' AND
                    coordinates = '$coordinates'";
            $result = $mysqli->query($query) or die(mysqli_error($mysqli));

            $num_rows = $result->num_rows;
        }
        if($num_rows == 0) {
            return false;
        } else {
            return true;
        }
        
    }
    
    /**
     * Description: Prints HTML table of all deposits.
     * 
     * @global object $mysqli
     * @global object $planets
     */
    function listDeposits() {
        global $mysqli;
        global $planets;
        
        $query = "SELECT * FROM deposits ORDER BY name asc";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        while($deposit = $result->fetch_array(MYSQLI_ASSOC)) {
            //Get planet name
            $planetInfo = $planets->planetInfo($deposit['planet_id']);
            $planetName = $planetInfo['name'];
            
            $HTML = "\n<br />\n
                     <br />
                     <div class='name'>%s</div>\n
                     <div class='size'>%u</div>\n
                     <div class='type'>%s</div>\n
                     <div class='planet_name'>%s</div>\n
                     <div class='edit_delete'>\n
                        \t<a href='editDeposit.php?id=%u' class='editLink'>Edit</a>\n
                        \t<a href='deleteDeposit.php?id=%u' onclick='return confirm_alert(this); return false;'
                        class='deleteLink'>Delete</a>\n
                     </div>";
            printf($HTML, $deposit['name'], $deposit['size'],
                    $deposit['type'], $planetName, $deposit['id'],
                    $deposit['id']);
        }
    }
    
    /**
     * 
     * Description: Changes corodinate, name, size, or type
     * of Raw material
     * 
     * @global object $mysqli
     * @param int $id
     * @param string $name
     * @param int $size
     * @param string $coordinates
     * @param string $type
     */
    function editDeposit($id, $name, $size, $coordinates, $type) {
        global $mysqli;
        
        // Get deposit info 
        $info = $this->depositInfo($id);
        $currCoord = $info['coordinates'];
        
        $hasDeposit = $this->hasDeposit(NULL, $info['planet_id'],  $coordinates);
        if($hasDeposit == true) {
            echo "Error: Deposit already there. <a href='listDeposits.php'>Try Again.</a>";
            die();
        }
        
        // do some error checking
        if(!isset($id) || empty($id)) {
            echo 'Error: ID cannot be empty. Please try again';
            exit();
        }
        
        // Check to see if planetID is an integer, if not try to cast it as one
        // and check again
        
        if(!is_numeric($id)) {
            $id = (int) $id;
            
            if(!is_numeric($id)) {
                echo 'Error: ID must be a number. Please try again.';
                exit();
            }
        }
        
        // check to see if name is set and not empty
        if(!isset($name) || empty($name)) {
            echo 'Error: Name cannot be empty. Please try again';
            exit();
        }
        
        if(!isset($size) || empty($size)) {
            echo 'Error: Size cannot be empty. Please try again';
            exit();
        }
        if(!is_numeric($size)) {
            $size = (int) $size;
            
            if(!is_numeric($size)) {
                echo 'Error: Size must be a number. Please try again.';
                exit();
            }
        }

        // Also check to make sure size is less than 30.
        if($size > 1000000 && $size < 0) {
            echo 'Error: Size must be greater than 0 and less than 30. Please try again.';
            exit();
        }
        
        if(!isset($coordinates) || empty($coordinates)) {
            echo 'Error: Coordinates cannot be empty. Please try again';
            exit();
        }
        
        // Right here if this was an app I was really going to use
        // I'd use explode() to grab the coordinates, using the "," as a delimeter
        // and cast both values as ints and make sure they didnt exceed $planetSize

        if(!isset($type)) {
            echo 'Error: Type cannot be empty. Please try again';
            exit();
        }
        
        // Check against array of types in terrain class.
        
        // Check to see if coordinates exist in database
        $sql = "SELECT id FROM deposits WHERE id = '$id' AND 
                coordinates = '$currCoord'";

        $result = $mysqli->query($sql) or die(mysqli_error($mysqli));
        $num_rows = $result->num_rows;
 
        // If everything is ok update the database
        // Probably an easier way to do this with joins maybe?
        // Someone should let me know -- Lane
        // Two different querys based on how many rows
        if($num_rows == 0) {
            $query = "INSERT INTO deposits VALUES ('', '', '$name',
                    '$size', '$coordinates', '$type')";
        } else {
            $query = "UPDATE deposits SET name = '$name', coordinates = '$coordinates', size = '$size',
                    type = '$type' WHERE id = '$id' AND coordinates = '$currCoord'";
        }

        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        header("Location: editDeposit.php?id=$id");
    }
    
    
    /**
     * Description: Deletes deposit where depositID = id
     * 
     * @global object $mysqli
     * @param int $depositID
     */
    function deleteDeposit($depositID) {
        global $mysqli;
        
        // Query to delete planet
        $query = "DELETE FROM deposits WHERE id = '$depositID'";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));
        
        header("Location: listDeposits.php");
    }
    
    
    /**
     * Description: Querys deposit database and returns array from
     * specified ID and coordinate.
     * 
     * @global object $mysqli
     * @param int $planetID
     * @param string $coordinates
     * @return array 
     */
    function getDeposit($planetID, $coordinates) {
        global $mysqli;
        
        $query = "SELECT * FROM deposits WHERE planet_id = '$planetID'
                AND coordinates = '$coordinates'";
        $result = $mysqli->query($query) or die(mysqli_errno($mysqli));
        
        $info = $result->fetch_array(MYSQLI_ASSOC);
        
        return $info;
        
    }
    
    /**
     * 
     * Description: Takes string argument and returns image url.
     * 
     * @param string $type
     * @return string
     */
    
    function depositImage($type) {
        $image = array(
            'Quantum'  => 'http://img.swcombine.com/materials/1/small.gif',
            'Meleenium' => 'http://img.swcombine.com/materials/2/small.gif',
            'Ardanium' => 'http://img.swcombine.com/materials/3/small.gif',
            'Rudic' => 'http://img.swcombine.com/materials/4/small.gif',
            'Ryll' => 'http://img.swcombine.com/materials/5/small.gif',
             'Duracrete' => 'http://img.swcombine.com/materials/6/small.gif',
            'Alazhi' => 'http://img.swcombine.com/materials/7/small.gif',
            'Laboi' => 'http://img.swcombine.com/materials/8/small.gif',
            'Adegan' => 'http://img.swcombine.com/materials/9/small.gif',
            'Rockivory' => 'http://img.swcombine.com/materials/10/small.gif',
            'Tibannagas' => 'http://img.swcombine.com/materials/11/small.gif',
            'Nova' => 'http://img.swcombine.com/materials/12/small.gif',
            'Varium' => 'http://img.swcombine.com/materials/13/small.gif',
            'Varmigio' => 'http://img.swcombine.com/materials/14/small.gif',
            'Lommite' => 'http://img.swcombine.com/materials/15/small.gif',
            'Hibridium' => 'http://img.swcombine.com/materials/16/small.gif',
            'Durelium' => 'http://img.swcombine.com/materials/17/small.gif',
            'Lowickan' => 'http://img.swcombine.com/materials/18/small.gif',
            'Vertex' => 'http://img.swcombine.com/materials/19/small.gif',
            'Berubian' => 'http://img.swcombine.com/materials/20/small.gif',
            'Bacta' => 'http://img.swcombine.com/materials/21/small.gif'
        );
        
        return $image[$type];    
    }
    
    
    /**
     * 
     * Description: Takes deposit id and returns array
     * 
     * @global object $mysqli
     * @param int $id
     * @return array
     */
    function depositInfo($id) {
        global $mysqli;
        
        $query = "SELECT * FROM deposits WHERE id = '$id'";
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));

        $info = $result->fetch_array(MYSQLI_ASSOC);

        return $info;
    }
    
}

?>
